package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.UnLikeBehaviorServcie;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UnLikeBehaviorServiceImpl implements UnLikeBehaviorServcie {
    @Autowired
    private CacheService cacheService;

    /**
     * 用户行为:不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult handlerUnLikesBehavior(UnLikesBehaviorDto dto) {
        //1.入参校验
        if (dto == null || dto.getArticleId() == null || dto.getType() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断是否登录
        ApUser apUser = ApUserThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.存入redis中 type=0,向redis中存入一条数据  type=1根据键删除redis中的记录数据
        if (dto.getType() == 0) {
            //不喜欢,向redis中存入一条数据
            log.info("用户行为-不喜欢,向redis中存入一条不喜欢的文章数据...");
            cacheService.hPut(BehaviorConstants.UNLIKES_BEHAVIOR + dto.getArticleId().toString(),
                    apUser.getId().toString(),
                    JSON.toJSONString(dto));
        } else {
            //取消不喜欢,删除redis中存入的数据
            cacheService.hDelete(BehaviorConstants.UNLIKES_BEHAVIOR + dto.getArticleId().toString(),
                    apUser.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
